<?php

/**
 * @file
 * Webform module reference component.
 */

/**
 * Implements _webform_defaults_component().
 */
function _webform_defaults_reference() {
  return array(
    'name' => '',
    'form_key' => NULL,
    'pid' => 0,
    'weight' => 0,
    'value' => '',
    'mandatory' => 0,
    'extra' => array(
      //'code_textfield' => 1,
      //'name_textfield' => 1,
      //'city_textfield' => 1,
      'searchpicker' => 1,
      'title_display' => 0,
      'description' => '',
      'private' => FALSE,
    ),
  );
}

/**
 * Implements _webform_theme_component().
 */
function _webform_theme_reference() {
  return array(
    'webform_reference' => array(
      'render element' => 'element',
      'file' => 'components/reference.inc',
    ),
    'webform_display_reference' => array(
      'render element' => 'element',
      'file' => 'components/reference.inc',
    ),
  );
}

/**
 * Implements _webform_edit_component().
 */
function _webform_edit_reference($component) {
  $form = array();
  $form['value'] = array(
    '#type' => 'textfield',
    '#title' => t('Default value'),
    '#default_value' => $component['value'],
    '#description' => t('The default value of the field.'),
    '#size' => 60,
    '#maxlength' => 127,
    '#weight' => 0,
  );

  $form['display']['searchpicker'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable popup search'),
    '#default_value' => $component['extra']['searchpicker'],
    '#description' => t('Enable a poup picker next to the field.'),
    '#weight' => 1,
    '#parents' => array('extra', 'searchpicker'),
  );
  /*$form['display']['code_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a textfield for Code'),
    '#default_value' => $component['extra']['code_textfield'],
    '#description' => t('If checked'),
    '#weight' => 2,
    '#parents' => array('extra', 'code_textfield'),
  );
  $form['display']['name_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a textfield for name'),
    '#default_value' => $component['extra']['name_textfield'],
    '#description' => t('If checked'),
    '#weight' => 3,
    '#parents' => array('extra', 'name_textfield'),
  );
  $form['display']['city_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a textfield for city'),
    '#default_value' => $component['extra']['city_textfield'],
    '#description' => t('If checked,'),
    '#weight' => 4,
    '#parents' => array('extra', 'city_textfield'),
  );*/

  return $form;
}

/**
 * Implements _webform_render_component().
 */
function _webform_render_reference($component, $value = NULL, $filter = TRUE) {
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;

  $element = array(
    '#type' => 'reference',
    '#title' => $filter ? _webform_filter_xss($component['name']) : $component['name'],
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
    '#weight' => $component['weight'],
    '#description' => $filter ? _webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
    '#required' => $component['mandatory'],
    //'#code_textfield' => $component['extra']['code_textfield'],
	//'#name_textfield' => $component['extra']['name_textfield'],
	//'#city_textfield' => $component['extra']['city_textfield'],
    '#default_value' => $filter ? _webform_filter_values($component['value'], $node, NULL, NULL, FALSE) : $component['value'],
    '#process' => array('webform_expand_reference'),
    '#theme' => 'webform_reference',
    '#theme_wrappers' => array('webform_element'),
    '#element_validate' => array('webform_validate_reference'),
    '#translatable' => array('title', 'description'),
  );

  if ($component['extra']['searchpicker']) {
    $element['#searchpicker'] = TRUE;
    //$element['#attached'] = array(
      //'library' => array(
       // array('system', 'ui.datepicker'),
      //),
    //);
  }

  // Set the value from Webform.
  if (isset($value[0]) && $value[0] !== '') {
	$value = webform_reference_array($value[0]);
    $element['#default_value'] = $value;
  }
  
  //print_r($element);exit;
  return $element;
}

// Convert an reference string into an array.
function webform_reference_array($string) {
  $return = array();
  
  $matches = explode("|", $string);
  
  $return['code'] = isset($matches[0]) ? $matches[0] : '';
  $return['name'] = isset($matches[1]) ? $matches[1] : '';
  $return['city'] = isset($matches[2]) ? $matches[2] : '';

  return $return;
}

/**
 * Provide a form for an example ajax modal button
 */
function webform_reference_ctools_button_form($country,$form_key) {
  $form = array();
    if($form_key=='receiving_company_legal_entity2'){
        $form['url'] = array(
            '#type' => 'hidden',
            // The name of the class is the #id of $form['ajax_button'] with "-url" suffix.
            '#attributes' => array('class' => array('ctools-ajax-sample-button-url')),
            '#value' => url('webformview/nojs/company/'.$country.'/1'),
        );
        $form['ajax_button'] = array(
            '#type' => 'button',
            '#value' => t('Search'),
            '#attributes' => array('class' => array('ctools-use-modal','legal-entity-search')),
            '#id' => 'ctools-ajax-sample-button',
        );
        drupal_add_js('function clear_legal_entity(){jQuery(\'#edit-submitted-relocation-data-receiving-company-legal-entity2-code\').val(\'\');jQuery(\'#edit-submitted-relocation-data-receiving-company-legal-entity2-name\').val(\'\');jQuery(\'#edit-submitted-relocation-data-receiving-company-legal-entity2-city\').val(\'\');return false;}', 'inline');
        $form['clear_button'] = array(
            '#type' => 'button',
            '#value' => t('Clear'),
            '#attributes' => array('onclick' => 'clear_legal_entity(); return false;'),
            '#id' => 'ctools-clear-button',
        );
    }
    if($form_key=='legal_entity_which_employee_signed_their_contract_for'){
        $form['url'] = array(
            '#type' => 'hidden',
            // The name of the class is the #id of $form['ajax_button'] with "-url" suffix.
            '#attributes' => array('class' => array('ctools-ajax-1-button-url')),
            '#value' => url('webformview/nojs/company/'.$country.'/2'),
        );
        $form['ajax_button'] = array(
            '#type' => 'button',
            '#value' => t('Search'),
            '#attributes' => array('class' => array('ctools-use-modal','legal-entity-search')),
            '#id' => 'ctools-ajax-1-button',
        );
        drupal_add_js('function clear_legal_entity_contract(){jQuery(\'#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-code\').val(\'\');jQuery(\'#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-name\').val(\'\');jQuery(\'#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-city\').val(\'\');return false;}', 'inline');
        $form['clear_button'] = array(
            '#type' => 'button',
            '#value' => t('Clear'),
            '#attributes' => array('onclick' => 'clear_legal_entity_contract(); return false;'),
            '#id' => 'ctools-clear-button',
        );
    }
  

  return $form;
}

/**
 * Form API #process function for Webform reference fields.
 */
function webform_expand_reference($element) {
  // Accept a string or array value for #default_value.
  if (!empty($element['#default_value']) && is_string($element['#default_value'])) {
	$element['#default_value'] = webform_reference_array($element['#default_value']);
  }

  // Set defaults according to existing #default_value (set by Form API)
  $default_values = array(
      'code' => isset($element['#default_value']['code']) ? $element['#default_value']['code'] : NULL,
      'name' => isset($element['#default_value']['name']) ? $element['#default_value']['name'] : NULL,
      'city' => isset($element['#default_value']['city']) ? $element['#default_value']['city'] : NULL,
  );

  // Let Drupal do it's normal expansion.
  //$element = form_process_date($element);	
  //print_r($element);exit;
  $nid = $element['#webform_component']['nid'];
  if (empty($element['#value'])) {
    $element['#value'] = array(
      'code' => 'code',
      'name' => 'name',
      'city' => 'city',
    );
  }
  $element['code'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Code'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['code'],
    '#attributes' => $element['#attributes'],
	//'#autocomplete_path' => 'webformview/services',
  );
  $element['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Name'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['name'],
    '#attributes' => $element['#attributes'],
	//'#autocomplete_path' => 'webformview/services',
  );
  $element['city'] = array(
    '#type' => 'textfield',
    '#title' => t('Company City'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['city'],
    '#attributes' => $element['#attributes'],
	//'#autocomplete_path' => 'webformview/services',
  );
  
  // Include the CTools tools that we need.
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js(); // Add CTools' javascript to the page.
  //$search = ctools_modal_text_button(t('Search'), 'webformview/nojs/company', t('Search'));
  
  //phase3 robert add
  $search_country = '';
  if (isset($_REQUEST['country'])) {
    $country = $_REQUEST['country'];
    $search_country = webform_get_nid_by_key($country);
  }
  if(!$search_country){
    $search_country = webform_get_country($nid);
  }

  if (arg(0) == 'node' && arg(2) == 'submission') {
    $sid = arg(3);
    $nid = arg(1);
    $country_data = submission_get_country($sid,$nid);
    $search_country['key'] = $country_data['key'];
  }
  //phase3 end
  $button_form = webform_reference_ctools_button_form($search_country['key'],$element['#webform_component']['form_key']);
  $search      = drupal_render($button_form);
  $element['searchbutton'] = array(
    '#type' => 'markup',
//    '#markup' => '<input type="button" id="search_button" name="search_button" value="Search" />',
	'#markup' => $search,
    '#attributes' => $element['#attributes'],
  );

  // Set default values.
  foreach ($default_values as $type => $value) {
    unset($element[$type]['#value']);
    $element[$type]['#default_value'] = isset($default_values[$type]) ? $default_values[$type] : NULL;
  }
  //print_r($element);exit;

  // Tweak the search button field.
  if ($element['#searchpicker']) {
	$element['code']['#size'] = 5;
	$element['name']['#size'] = 30;
	$element['city']['#size'] = 10;
  }
  else {
    unset($element['searchbutton']);
  }

  return $element;
}

/**
 * Theme a webform reference element.
 */
function theme_webform_reference($variables) {
  $element = $variables['element'];

  if ($element['#searchpicker']) {
    if ($element['#required']) {
      $element['code']['#attributes']['class'] = array('code','required');
      $element['name']['#attributes']['class'] = array('name','required');
      $element['city']['#attributes']['class'] = array('city','required');
    }else{
      $element['code']['#attributes']['class'] = array('code');
      $element['name']['#attributes']['class'] = array('name');
      $element['city']['#attributes']['class'] = array('city');
    }
  }
  else {
  }

  // Add error classes to all items within the element.
  if (form_get_error($element)) {
    if ($element['#searchpicker']) {
	  $element['code']['#attributes']['class'][] = 'error';
      $element['name']['#attributes']['class'][] = 'error';
      $element['city']['#attributes']['class'][] = 'error';
	}
	else {
	}
  }

  $class = array('webform-container-inline');

  // Add the JavaScript calendar if available (provided by Date module package).
  /*if (!empty($element['#datepicker'])) {
    $class[] = 'webform-datepicker';
    $calendar_class = array('webform-calendar');
    if ($element['#start_date']) {
      $calendar_class[] = 'webform-calendar-start-' . $element['#start_date'];
    }
    if ($element['#end_date']) {
      $calendar_class[] = 'webform-calendar-end-' . $element['#end_date'];
    }
    $calendar_class[] ='webform-calendar-day-' . variable_get('date_first_day', 0);

    $calendar = theme('webform_calendar', array('component' => $element['#webform_component'], 'calendar_classes' => $calendar_class));
  }*/

  $output = '';
  $output .= '<div class="' . implode(' ', $class) . '"> ';
  $output .= drupal_render_children($element);
  //$output .= isset($calendar) ? $calendar : '';
  $output .= '</div>';

  return $output;
}

/**
 * Element validation for Webform date fields.
 */
function webform_validate_reference($element, $form_state) {
  // Check if the user filled the required fields.
//  if ($element['#required']) {
//    if (!isset($element['code']) || strlen(trim($element['code']['#value']))<=0) {
//      form_error($element, t('!name field is required.', array('!name' => $element['code']['#title'])));
//      return;
//    }
//	
//	$company_code = trim($element['code']['#value']);
//	$company = company_get_list(WEBFORM_DEFAULT_COUNTRY, $company_code);
//	if (!isset($company['company_code']) || $company['company_code']!=$company_code) {
//	  form_error($element, t('!name field is not available.', array('!name' => $element['code']['#title'])));
//      return; 
//	}
//  }
}

// Convert an array of a reference into a string.
function webform_reference_string($array) {
  $string = '';
  
  $i = 1;
  $arr = array('code', 'name', 'city');
  foreach ($arr as $field_type) {
	if (isset($array[$field_type])) {
	  $tag = ($i==count($arr)) ? "" : "|";
	  $string .= $array[$field_type].$tag;
	}
	$i++;
  }//echo $string;exit;
  
  return $string;
}

/**
 * Implements _webform_submit_component().
 */
function _webform_submit_reference($component, $value) {
  // Convert to a string.
  //print_r($component);print_r($value);exit;
  return webform_reference_string($value);
}

/**
 * Implements _webform_display_component().
 */
function _webform_display_reference($component, $value, $format = 'html') {
  if (isset($value[0]) && $value[0] !== '') {
	$value = webform_reference_array($value[0]);
  }
  
  return array(
    '#title' => $component['name'],
    '#weight' => $component['weight'],
    '#theme' => 'webform_display_reference',
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
    '#format' => $format,
    '#value' => $value,
    '#translatable' => array('title'),
  );
}

/**
 * Format the text output for this component.
 */
function theme_webform_display_reference($variables) {
  $element = $variables['element'];
  $empty_tag = "&nbsp;";
  if($element['#format'] == 'text') {
    $empty_tag = " ";
  }
  $comma = ',';
  $output = ' ';
  if (isset($element['#value']['code'])) {
	$output .= t("Code:") ." ".trim($element['#value']['code']). $comma. $empty_tag;
  }
  if (isset($element['#value']['name'])) {
	$output .= t("Name:") ." " . trim($element['#value']['name']). $comma. $empty_tag;
  }
  if (isset($element['#value']['city'])) {
	$output .= t("City:")." ". trim($element['#value']['city']).$empty_tag;
  }
  //echo $output;exit;
  return $output;
}

/**
 * Implements _webform_analysis_component().
 */
function _webform_analysis_reference($component, $sids = array()) {
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
    ->fields('wsd', array('no', 'data'))
    ->condition('nid', $component['nid'])
    ->condition('cid', $component['cid'])
    ->orderBy('sid');

  if (count($sids)) {
    $query->condition('sid', $sids, 'IN');
  }

  $result = $query->execute();

  $dates = array();
  $submissions = 0;
  foreach ($result as $row) {
    $submissions++;
    if ($row['data']) {
      $dates[] = webform_reference_array($row['data']);
    }
  }

  // Display stats.
  $nonblanks = count($dates);
  $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
  $rows[1] = array(t('User entered value'), $nonblanks);
  return $rows;
}

/**
 * Implements _webform_table_component().
 */
function _webform_table_reference($component, $value) {
  if ($value[0]) {
	return $value[0];
  }
  else {
    return '';
  }
}

/**
 * Implements _webform_csv_headers_component().
 */
function _webform_csv_headers_reference($component, $export_options) {
  $header = array();
  $header[0] = '';
  $header[1] = '';
  $header[2] = $component['name'];
  return $header;
}

/**
 * Implements _webform_csv_data_component().
 */
function _webform_csv_data_reference($component, $export_options, $value) {
  if ($value[0]) {
	return $value[0];
  }
  else {
    return '';
  }
}
